package com.novax.ex.activity.provider.service;

import com.alibaba.fastjson.JSON;
import com.novax.ex.activity.infrastructure.entity.*;
import com.novax.ex.activity.infrastructure.mapper.MallOrderWinnerMapper;
import com.novax.ex.activity.infrastructure.mapper.MallOrderWinnerMemosMapper;
import com.novax.ex.activity.infrastructure.mapper.MallPrizeOrderMapper;
import com.novax.ex.activity.infrastructure.mapper.MallProductMapper;
import com.novax.ex.activity.open.model.query.MallWinnerQuery;
import com.novax.ex.activity.open.model.response.MallMsgResponse;
import com.novax.ex.activity.open.model.response.MallOrderWinnerResponse;
import com.novax.ex.activity.open.model.response.ParticipationRecordResponse;
import com.novax.ex.activity.provider.api.InternationalApi;
import com.novax.ex.activity.provider.handler.provider.MallProductProvider;
import com.novax.ex.common.base.BaseMapper;
import com.novax.ex.common.base.BaseService;
import com.novax.ex.common.constant.InternationalCode;
import com.novax.ex.common.enums.MallOrderWinnerMemosStatus;
import com.novax.ex.common.enums.MallOrderWinnerStatus;
import com.novax.ex.common.enums.MallPrizeOrderStatus;
import com.novax.ex.common.enums.MallProductStatus;
import com.novax.ex.common.results.ReturnResult;
import com.novax.ex.common.util.CopyUtils;
import com.novax.ex.common.util.PageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import jakarta.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Description 中奖订单记录表Service
 * @Author zhaolei
 * @Date 2/21/23 5:35 PM
 * @Version 1.0
 */
@Slf4j
@Service
public class MallOrderWinnerService extends BaseService {
    @Resource
    private MallOrderWinnerMapper mallOrderWinnerMapper;
    @Resource
    private InternationalApi internationalApi;
    @Resource
    private MallProductTitleLanguageService mallProductTitleLanguageService;
    @Resource
    private MallPrizeOrderService mallPrizeOrderService;
    @Resource
    private MallProductProvider mallProductProvider;
    @Resource
    private MallProductMapper mallProductMapper;
    @Resource
    private MallPrizeOrderMapper mallPrizeOrderMapper;
    @Resource
    private MallOrderWinnerMemosMapper mallOrderWinnerMemosMapper;

    @Override
    protected BaseMapper getBaseMapper() {
        return mallOrderWinnerMapper;
    }

    /**
     * @description: 获取消息
     * @author: Wade
     * @date: 2/22/23 5:29 PM
     * @param: [language]
     * @return: java.util.List<com.novax.ex.activity.open.model.response.MallMsgResponse>
     **/
    public List<MallMsgResponse> msgList(String language) {
        //查询中奖信息
        List<MallOrderWinner> prizeOrders = mallOrderWinnerMapper.selectMsg();
        String msg = internationalApi.getInternational(InternationalCode.USER_MALL_ORDER_WINNER_MSG, language).getData();
        List<MallMsgResponse> mallMsgResponses = new ArrayList<>();
        for (MallOrderWinner prizeOrder : prizeOrders) {
            MallMsgResponse response = new MallMsgResponse();
            String title = mallProductTitleLanguageService.getTitleByLanguage(prizeOrder.getMallProductId(), language);
            response.setMessage(mallPrizeOrderService.replaceMsg(prizeOrder.getNickname(), title, msg));
            mallMsgResponses.add(response);
        }
        return mallMsgResponses;
    }

    /**
     * @description: 详情页获取消息
     * @author: Wade
     * @date: 2/22/23 5:29 PM
     * @param: [language]
     * @return: java.util.List<com.novax.ex.activity.open.model.response.MallMsgResponse>
     **/
    public List<MallMsgResponse> msgDetailList(String language, Long productId) {
        //查询中奖信息
        List<MallOrderWinner> prizeOrders = mallOrderWinnerMapper.selectDetailMsg(productId);
        String msg = internationalApi.getInternational(InternationalCode.USER_MALL_ORDER_WINNER_DETAIL_MSG, language).getData();
        List<MallMsgResponse> mallMsgResponses = new ArrayList<>();
        for (MallOrderWinner prizeOrder : prizeOrders) {
            MallMsgResponse response = new MallMsgResponse();
            //String title = mallProductTitleLanguageService.getTitleByLanguage(prizeOrder.getMallProductId(),language);
            response.setMessage(mallPrizeOrderService.replaceMsg(prizeOrder.getNickname(), "", msg));
            mallMsgResponses.add(response);
        }
        return mallMsgResponses;
    }

    /**
     * 商品销售报表
     */
    public <T> void salesPage(PageUtil<T> pageInfo, Class<T> clazz) {
        long total = mallOrderWinnerMapper.salesCount(pageInfo);
        pageInfo.setTotal(total);
        if (total > 0) {
            pageInfo.setItems(CopyUtils.copyList(mallOrderWinnerMapper.salesPage(pageInfo), clazz));
        } else {
            pageInfo.setItems(new ArrayList<>());
        }
    }

    /**
     * 商品获得明细
     */
    public <T> void itemPage(PageUtil<T> pageInfo, Class<T> clazz) {
        long total = mallOrderWinnerMapper.itemCount(pageInfo);
        pageInfo.setTotal(total);
        if (total > 0) {
            pageInfo.setItems(CopyUtils.copyList(mallOrderWinnerMapper.itemPage(pageInfo), clazz));
        } else {
            pageInfo.setItems(new ArrayList<>());
        }
    }

    @Transactional
    public void prize(MallPrizeLottery lottery) {
        //判断中奖记录中是否存在记录，如果存在记录说明开过奖了，直接返回null
        Map<String, Object> map = new HashMap<>();
        map.put("mallPrizeId", lottery.getMallPrizeId());
        List<MallOrderWinner> winners = mallOrderWinnerMapper.selectList(map);
        if (CollectionUtils.isEmpty(winners)) {
            MallPrizeOrder mallPrizeOrder = mallPrizeOrderService.find(lottery.getMallPrizeOrderId());
            MallOrderWinner winner = CopyUtils.copyObject(mallPrizeOrder, MallOrderWinner.class);
            winner.setId(null);
            winner.setMallPrizeOrderId(mallPrizeOrder.getId());
            winner.setMallPrizeLotteryId(lottery.getId());
            winner.setStatus(MallOrderWinnerStatus.noSay.getStatus());
            winner.setCreateTime(null);
            winner.setUpdateTime(null);
            winner.setMemo(null);
            addSelective(winner);//插入中奖表信息
            //修改用户订单状态为3.已参与或4.待领取*/
            //修改3状态，通过本批次奖品池的奖品id统一改为3
            mallPrizeOrderService.updateParticipated(lottery.getMallPrizeId());
            //按照中奖的mallPrizeOrderId 改为4
            MallPrizeOrder norder = new MallPrizeOrder();
            norder.setId(mallPrizeOrder.getId());
            norder.setStatus(MallPrizeOrderStatus.unclaimed.getStatus());
            mallPrizeOrderService.modifySelective(norder);

            //商品生产奖品后扣商品库存，这样防止超卖
            mallProductMapper.subStock(lottery.getMallProductId());
            //触发下一次奖品生产
            MallProduct product = mallProductMapper.selectByPrimaryKey(lottery.getMallProductId());
            if (product.getStockCount().intValue() == 0) {
                //商品下架
                MallProduct mallProduct = new MallProduct();
                mallProduct.setId(lottery.getMallProductId());
                mallProduct.setStatus(MallProductStatus.down.getStatus());
                mallProductMapper.updateByPrimaryKeySelective(mallProduct);
            } else {
                mallProductProvider.sendPutOn(JSON.toJSONString(product));
            }
        }
    }

    @Transactional
    public boolean statusChange(Long id, Long mallPrizeOrderId, Integer creatorType, Long adminId, Integer status, Integer oldStatus) {
        // 用户订单状态与奖品发放状态联动
        if(MallOrderWinnerStatus.sendEntity.getStatus().equals(status)
                || MallOrderWinnerStatus.sendUSDT.getStatus().equals(status)){
            // 更新订单
            MallPrizeOrder order = new MallPrizeOrder();
            order.setId(mallPrizeOrderId);
            order.setStatus(MallPrizeOrderStatus.received.getStatus());
            mallPrizeOrderService.modifySelective(order);
        }
        // 更新中奖记录
        MallOrderWinner entity = new MallOrderWinner();
        entity.setId(id);
        entity.setStatus(status);
        mallOrderWinnerMapper.updateByPrimaryKeySelective(entity);
        // 中奖记录备注
        MallOrderWinnerMemos memo = new MallOrderWinnerMemos();
        memo.setMallOrderWinnerId(id);
        memo.setOldStatus(oldStatus);
        memo.setCreatorType(creatorType);
        memo.setCreator(adminId);
        memo.setNewStatus(status);
        memo.setOperationType(MallOrderWinnerMemosStatus.changeStatus.getStatus());
        memo.setMemo("");
        int memoResult = mallOrderWinnerMemosMapper.insertSelective(memo);
        return memoResult > 0;
    }

    /**
     * Description: 批量查询数据
     *
     * @author Deucalion@novax.email
     * @date 2023/4/11 13:50
     */
    public List<MallOrderWinner> findByIds(Set<String> ids){
        return mallOrderWinnerMapper.selectOldData(ids);
    }

    /***
     * Description: 状态变更
     *
     * @return boolean
     * @author Deucalion@novax.email
     * @date 2023/3/31 10:45
     */
    @Transactional
    public boolean batchStatusChange(Set<String> ids,Integer creatorType,Long adminId,Integer status) {
        // 旧数据列表
        List<MallOrderWinner> oldData = mallOrderWinnerMapper.selectOldData(ids);
        // 变更内容
        List<MallOrderWinner> list = new ArrayList<>();
        List<MallOrderWinnerMemos> memos = new ArrayList<>();
        List<MallPrizeOrder> orders = new ArrayList<>();
        for (MallOrderWinner orderWinner: oldData) {
            // 中奖记录备注
            MallOrderWinnerMemos memo = new MallOrderWinnerMemos();
            memo.setMallOrderWinnerId(orderWinner.getId());
            memo.setOldStatus(orderWinner.getStatus());
            memo.setCreatorType(creatorType);
            memo.setCreator(adminId);
            memo.setNewStatus(status);
            memo.setOperationType(MallOrderWinnerMemosStatus.changeStatus.getStatus());
            memo.setMemo("");
            memos.add(memo);
            // 订单
            if(MallOrderWinnerStatus.sendEntity.getStatus().equals(status)
                    || MallOrderWinnerStatus.sendUSDT.getStatus().equals(status)){
                MallPrizeOrder order = new MallPrizeOrder();
                order.setId(orderWinner.getMallPrizeOrderId());
                order.setStatus(MallPrizeOrderStatus.received.getStatus());
                orders.add(order);
            }
            // 中奖记录
            MallOrderWinner record = new MallOrderWinner();
            record.setId(orderWinner.getId());
            record.setStatus(status);
            record.setMemo("");
            list.add(record);
        }
        // 记录备注
        int memosLine = mallOrderWinnerMemosMapper.batchInsert(memos);
        // 用户订单状态与奖品发放状态联动
        int orderLine = 0;
        if(orders.size() > 0){
            orderLine = mallPrizeOrderMapper.batchStatusChange(orders);
        }
        //更新中奖记录
        int statusChangeLine = 0;
        if(MallOrderWinnerStatus.success.getStatus().equals(status)){
            statusChangeLine = mallOrderWinnerMapper.batchStatusChangeEnd(list);
        }else{
            statusChangeLine = mallOrderWinnerMapper.batchStatusChangeGive(list);
        }
        log.debug("memosLine:{},statusChangeLine:{},orderLine:{}",memosLine,statusChangeLine,orderLine);
        return (memosLine > 0 || statusChangeLine > 0 || orderLine > 0);
    }

    /**
     * @description: 查询是否存在中奖未领取的
     * @author: Wade
     * @date: 3/7/23 11:20 AM
     * @param: [userId]
     **/
    public MallOrderWinner unclaimed(Long userId) {
        return mallOrderWinnerMapper.unclaimed(userId);
    }

    /**
     * @description: 查询往期中奖记录
     * @author: Wade
     * @date: 3/16/23 3:05 PM
     **/
    public <T> void winnersPage(PageUtil<T> pageInfo, Class<T> clazz) {
        long total = mallOrderWinnerMapper.winnersCount(pageInfo);
        pageInfo.setTotal(total);
        if (total > 0) {
            pageInfo.setItems(CopyUtils.copyList(mallOrderWinnerMapper.winnersPage(pageInfo), clazz));
        } else {
            pageInfo.setItems(new ArrayList<>());
        }
    }

    public MallOrderWinner getWinnerNew(Long userId) {
        return mallOrderWinnerMapper.getWinnerNew(userId);
    }

    public void setWinnerNewTag(Long id) {
        mallOrderWinnerMapper.setWinnerNewTag(id);
    }

    /** 备注修改 */
    public boolean memoChange(MallOrderWinner entity, Integer creatorType, Long adminId) {
        // 中奖记录备注
        MallOrderWinnerMemos memo = new MallOrderWinnerMemos();
        memo.setMallOrderWinnerId(entity.getId());
        memo.setCreatorType(creatorType);
        memo.setCreator(adminId);
        memo.setOperationType(MallOrderWinnerMemosStatus.changeStatus.getStatus());
        memo.setMemo(entity.getMemo());
        mallOrderWinnerMemosMapper.insertSelective(memo);
        // 中奖信息变更
        return mallOrderWinnerMapper.updateByPrimaryKeySelective(entity) > 0;
    }
}
